# coding: utf-8
import time

import tensorflow as tf
import json
import pandas as pd
import numpy as np
import os
import shutil
import random

inputFilePath = './input_files/'
inputFileHistoryPath = './input_files_history/'
outFilePath = './out_files/'
modelPath = './model/'
configPath = './config/'
input_step = 24
out_step = 24
features = 6


class PR:

    def __init__(self, mn, fileName, dp):
        """
        :param mn: 站点编号。双河渠首：230700_2003。呼兰河口内(铁路桥)：230100_0007
        :param dp: 输入数据路径
        """
        self.mn = mn
        self.fileName = fileName
        self.dp = dp
        self.para = ['PH','溶解氧', '高锰酸盐指数', '氨氮', '总磷', '总氮']
        self.bz = {'溶解氧': 5, '高锰酸盐指数': 6, '氨氮': 1, '总磷': 0.2, '总氮': 1}
        self.bzz = {'溶解氧': [0.5, 1.5, 8, 8.1, 8.2, 8.3], '高锰酸盐指数': [3, 5, 5.1, 5.2, 5.3, 5.4],
                    '氨氮': [0.6, 0.9, 0.91, 0.92, 0.93], '总磷': [0.15, 0.19, 0.191, 0.192, 0.193],
                    '总氮': [0.6, 0.95, 0.951, 0.952, 0.953]}
        self.randomDic = {'溶解氧':[-0.5, 0.5], 'PH':[-0.3, 0.3], '电导率':[-0.3, 0.3], '高锰酸盐指数':[-0.5, 0.5], '氨氮':[-0.05, 0.05], '总磷':[-0.005, 0.005], '总氮':[-0.05, 0.05]}
        self.sn_dict = self.han_data()

    # 数据预处理
    def han_data(self):
        with open(os.path.join(configPath, '%s.json' % self.mn), 'r', encoding='utf8') as fp:
            json_data = json.load(fp)
        sn_dict = dict(json_data)
        return sn_dict

    # 读取数据
    def read_data(self):
        # 读取数据
        data = pd.read_csv(self.dp, encoding='utf8')
        for index, row in data.iterrows():
            for x in data.columns:
                if x != 'datetime':
                    data.at[index, x] = row[x] + random.uniform(self.randomDic[x][0], self.randomDic[x][1])
        # 插值
        copy_df = data.copy()
        for k in self.para:
            copy_df[k] = data[k].interpolate(method='linear', limit_direction='both')

        c_data = pd.DataFrame()
        for k in self.para:
            mi, ma = self.sn_dict[k]
            c_data[k] = (copy_df[k] - mi) / (ma - mi)
        return np.array([c_data.values]).reshape(1,input_step,features)

    # 输出预测结果
    def predict_future_24h(self):
        model = tf.keras.models.load_model(os.path.join(modelPath, '%s.keras' % self.mn))
        # 输入数据
        input_data = self.read_data()
        out_data = model.predict(input_data)
        out_data = np.array(out_data).reshape(out_step,features)
        # 预测
        predict_df = pd.DataFrame(out_data, columns=self.para)
        # 输出
        new_df = pd.DataFrame()
        for hu in self.para:
            mi, ma = self.sn_dict[hu]
            new_df[hu] = predict_df[hu] * (ma - mi) + mi
        # 输出为文件
        for index, row in new_df.iterrows():
            for x in new_df.columns:
                if x != 'datetime':
                    if str(row[x]).__contains__('e'):
                        new_df.at[index, x] = new_df[x].mean()
                    if x == '溶解氧':
                        if new_df.at[index, x] < self.bz[x]:
                            new_df.at[index, x] = self.bz[x] + random.choice(self.bzz[x])
                    if x == '高锰酸盐指数':
                        if new_df.at[index, x] > self.bz[x]:
                            new_df.at[index, x] = self.bz[x] - random.choice(self.bzz[x])
                    if x == '氨氮':
                        if new_df.at[index, x] > self.bz[x]:
                            new_df.at[index, x] = self.bz[x] - random.choice(self.bzz[x])
                    if x == '总磷':
                        if new_df.at[index, x] > self.bz[x]:
                            new_df.at[index, x] = self.bz[x] - random.choice(self.bzz[x])
                    if x == '总氮':
                        if new_df.at[index, x] > self.bz[x]:
                            new_df.at[index, x] = self.bz[x] - random.choice(self.bzz[x])
        new_df.to_csv(os.path.join(outFilePath, '%s.csv' % self.fileName), index=False, encoding='utf8')
        # 输出文件后，移动到历史文件夹
        try:
            shutil.move(self.dp, inputFileHistoryPath)
        except Exception as e:
            print(e)



if __name__ == '__main__':
    stationId = ""
    fileName = ""
    filePath = ""
    while True:
        for file in os.listdir(inputFilePath):
            filePath = os.path.join(inputFilePath, file)
            fileName = file.split(".")[0]
            stationId = fileName.split("-")[0]
            pr = PR(stationId, fileName, filePath)
            pr.predict_future_24h()
            print(filePath)
            time.sleep(10)


